﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using Citi.FinancePlanningAnalysis.Domain;
using Citi.FinancePlanningAnalysis.SchedulerUi.SchedulerWcf;
using Citi.RoutineBase;

namespace Citi.FinancePlanningAnalysis.SchedulerUi
{
    public class PearlImport : GeneralImport
    {
        public new IEnumerable<RoutineParameter> Parameters
        {
            get
            {
                return new List<RoutineParameter> { 
                    new RoutineParameter{ Description = "If you want to start a routine when it's finished, insert the Routine Id.", 
                        Name ="SuccessorRoutineId", Nullable = true, Required = false, Type = typeof(int)}
                };
            }
        }

        public override string ExcelPath { get { return ConfigurationManager.AppSettings["PearlExcelPath"]; } }
        public override List<string> Files { get; set; }
        public override string QueryMergeDate { get { return Pearl.QueryMergeDate; } }
        public override string QueryDeletePrevious { get { return Pearl.QueryDeletePrevious; } }
        public override string QueryExcel { get { return Pearl.QueryExcel; } }
        public override string TableTemp { get { return "PearlTemp"; } }
        public override Dictionary<string, string> ExcelColumnMappings { get { return Pearl.ExcelColumnMappings; } }
        public override string SheetName { get { return string.Format("tb_QRY_Pearl_{0}", DateTime.Today.Year); } }

        public override void PrepareFiles(DateTime scheduledDate, RoutineBase.ICurrentAction currentAction, Dictionary<string, object> parameters)
        {
            currentAction.Description = string.Format("Looking for file in {0}", ExcelPath);
            Files = Directory.GetFiles(ExcelPath).Where(x => x.EndsWith(".xlsx")).ToList(); 
        }

        public override void FinishImport(ICurrentAction currentAction, Dictionary<string, object> parameters)
        {
            var successorRoutineId = parameters.ContainsKey("SuccessorRoutineId") ? parameters["SuccessorRoutineId"].ToString() : null;

            if (!string.IsNullOrWhiteSpace(successorRoutineId))
                SetSucessorRoutine(int.Parse(successorRoutineId), currentAction);
        }
        
        private void SetSucessorRoutine(int successorRoutineId, ICurrentAction currentAction)
        {
            if (successorRoutineId <= 0) return;

            currentAction.Description = "Scheduling successor routine";

            using (var client = new ScheduleClient())
                client.ExecuteRoutineOnDemandById(successorRoutineId, null);

            currentAction.Description = "Successor routine scheduled. It will be executed as soon as possible";
        }
    }
    //public class PearlImport : IExecutableRoutine
    //{
    //    public IEnumerable<RoutineParameter> Parameters
    //    {
    //        get
    //        {
    //            return new List<RoutineParameter> { 
    //                new RoutineParameter{ Description = "If you want to start a routine when it's finished, insert the Routine Id.", 
    //                    Name ="SuccessorRoutineId", Nullable = true, Required = false, Type = typeof(int)}
    //            };
    //        }
    //    }

    //    private string DatabaseConnectionString { get { return ConfigurationManager.AppSettings["DatabaseConnectionString"]; } }
    //    private string ExcelConnectionString { get { return ConfigurationManager.AppSettings["ExcelConnectionString"]; } }
    //    private string ExcelPath { get { return ConfigurationManager.AppSettings["PearlExcelPath"]; } }

    //    public void Rollback(ref ICurrentAction currentAction, Dictionary<string, object> parameters)
    //    {

    //    }

    //    public void Start(DateTime scheduledDate, ref ICurrentAction currentAction, Dictionary<string, object> parameters)
    //    {
    //        var importedPath = Path.Combine(ExcelPath, "Imported");

    //        if (!Directory.Exists(importedPath))
    //            Directory.CreateDirectory(importedPath);

    //        currentAction.Description = string.Format("Looking for file in {0}", ExcelPath);
    //        var files = Directory.GetFiles(ExcelPath).Where(x => x.EndsWith(".xlsx"));

    //        if (!files.Any())
    //        {
    //            currentAction.Description = "No files were found.";
    //            throw new Exception("No files were found.");
    //        }

    //        DeletePreviousData(currentAction);

    //        foreach (var file in files)
    //        {
    //            currentAction.Description = string.Format("{0} found", Path.GetFileName(file));
    //            currentAction.Description = "Copying data";
    //            SqlHelper.CopyExcelToSql(string.Format(ExcelConnectionString, file), Pearl.QueryExcel,
    //                "PearlTemp", DatabaseConnectionString, Pearl.ExcelColumnMappings, string.Format("tb_QRY_Pearl_{0}", DateTime.Today.Year));

    //            currentAction.Description = "Moving file to import folder";
    //            var importedFile = Path.Combine(importedPath, Path.GetFileName(file));

    //            if (File.Exists(importedFile)) File.Delete(importedFile);
    //            File.Move(file, importedFile);
    //        }

    //        MergeData(currentAction);

    //        var successorRoutineId = parameters.ContainsKey("SuccessorRoutineId") ? parameters["SuccessorRoutineId"].ToString() : null;

    //        if (!string.IsNullOrWhiteSpace(successorRoutineId))
    //            SetSucessorRoutine(int.Parse(successorRoutineId), currentAction);
    //    }

    //    private void SetSucessorRoutine(int successorRoutineId, ICurrentAction currentAction)
    //    {
    //        if (successorRoutineId <= 0) return;

    //        currentAction.Description = "Scheduling successor routine";

    //        using (var client = new ScheduleClient())
    //            client.ExecuteRoutineOnDemandById(successorRoutineId, null);

    //        currentAction.Description = "Successor routine scheduled. It will be executed as soon as possible";
    //    }

    //    private void MergeData(ICurrentAction currentAction)
    //    {
    //        currentAction.Description = "Merging data";
    //        currentAction.Description = Pearl.QueryMergeDate;
    //        SqlHelper.ExecuteNonQuery(Pearl.QueryMergeDate, DatabaseConnectionString);
    //    }

    //    private void DeletePreviousData(ICurrentAction currentAction)
    //    {
    //        currentAction.Description = "Deleting Previous Data";
    //        currentAction.Description = Pearl.QueryDeletePrevious;
    //        SqlHelper.ExecuteNonQuery(Pearl.QueryDeletePrevious, DatabaseConnectionString);
    //    }

    //    public void Stop(ref ICurrentAction currentAction, Dictionary<string, object> parameters)
    //    {

    //    }
    //}
}
